#include <filesystem>
#include <fairlogger/Logger.h>
// void run_unpacker(const Char_t *inputFile="Raw_Test.list", const Char_t *Save_dir="../../ROOTData")
string GetOutputFileName(string inputFile);
void run_unpack(const string inputFile =
    "/public/BeamTest_Nov2023/Test/20251021_3/data_EBS1_1_1_20251021T171035_0.dat",
    const string Save_dir = "/public/HIRIBL_Data/RawRootData/")
{

	string HiDir = getenv("VMCWORKDIR");

    string inputFile_str = inputFile; // end with .dat/.list/.online
    string parFile = HiDir + "/macro/params.root";
    string outFile = "Unpack.root";
    // string outFile = Save_dir + GetOutputFileName(inputFile);
    // std::filesystem::create_directories(std::filesystem::path(outFile).parent_path());

    bool OutFileNameFromInFile = true;
    Int_t MaxTSNum_User = 10000; // 用户指定最大解包时间片数量，默认 10000
    TStopwatch timer;

    // FairLogger::GetLogger()->SetLogScreenLevel("debug2"); //Old version
    // fair::Logger::SetConsoleSeverity("debug2"); //New version
    // fair::Logger::SetConsoleSeverity("state"); //New version 
    fair::Logger::SetConsoleColor(true);
    //------------ Basic Setting for FairRun----------------------------------    
    FairRunAna *fRun = new FairRunAna();
    // FairFileSource *fFileSource = new FairFileSource(inFile);
    // fRun->SetSource(fFileSource);
    fRun->SetSink(new FairRootFileSink(outFile)); 
    fRun->SetUseFairLinks(kFALSE);

    // -----  Parameter database   --------------------------------------------

    // FairRuntimeDb*  rtdb = fRun->GetRuntimeDb();
    // FairParRootFileIo* parInput1 = new FairParRootFileIo();
    // parInput1->open(parFile.c_str());
    // rtdb->setFirstInput(parInput1);
    // rtdb->Print();

    //============Task Sequence===============================================
    HiDaqUnpackTask* basicUnpacker = new HiDaqUnpackTask(inputFile, kTRUE);
    fRun->AddTask(basicUnpacker);

    HiMusicUnpackTask* musicUnpacker = new HiMusicUnpackTask(basicUnpacker, kTRUE);
    fRun->AddTask(musicUnpacker);

    HiSmdUnpackTask* smdUnpacker = new HiSmdUnpackTask(basicUnpacker, kTRUE);
    fRun->AddTask(smdUnpacker);

    HiTofUnpackTask* tofUnpacker = new HiTofUnpackTask(basicUnpacker, kTRUE);
    fRun->AddTask(tofUnpacker);

    HiTpcUnpackTask* tpcUnpacker = new HiTpcUnpackTask(basicUnpacker, kTRUE);
    fRun->AddTask(tpcUnpacker);
    //============Init and run================================================
    fRun->Init();
    

    timer.Start();
    int MaxTSNum_Real = basicUnpacker->GetTotalTSNum();
    LOG(info) << "Unpacking " << TMath::Min(MaxTSNum_Real, MaxTSNum_User) << " TimeSlices...";
    fRun->Run(0, TMath::Min(MaxTSNum_Real, MaxTSNum_User));
    // fRun->Run(0, 1);

    //----------------------------------------------------------------------
    timer.Stop();
    Double_t rtime = timer.RealTime();
    Double_t ctime = timer.CpuTime();
    cout << endl << endl;
    cout << "Tasks finished successfully"<<endl;
    cout << "Output file is "    << outFile << endl;
    cout << "Real time " << rtime << " s, CPU time " << ctime << " s" << endl;
    cout << endl;

} 

string GetOutputFileName(string inputFile){
    // Generate output file name based on input file name

    std::filesystem::path inputPath(inputFile);
    // 1. 提取文件名（不带扩展名）
    string filename = inputPath.stem().string(); 
    // 2. 检查上一级目录是否包含 "2025*"
    if (inputPath.has_parent_path()) {
        std::string parentDir = inputPath.parent_path().filename().string();
        // 检查是否包含 "2025"
        if (parentDir.rfind("2025", 0) == 0) {  // rfind("2025",0)==0 表示以“2025”开头
            filename = parentDir + "/" + filename;
            return filename + ".root";
        }
    }
    // 如果不满足条件，直接返回文件名.root
    return filename + ".root";

}